<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="请购单号" prop="planId">
        <el-input
          v-model="queryParams.planId"
          placeholder="请输入请购单号"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="rowList">
      <el-table-column label="请购单号" align="center" prop="planId" width="180" fixed="left"/>
      <el-table-column label="请购名称" align="center" prop="name" width="180"/>
      <el-table-column label="园区" align="center" prop="area" width="120"/>
      <el-table-column label="供应商名称" align="center" prop="vendorName" width="150"/>
      <el-table-column label="请购日期" align="center" prop="planTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
       <el-table-column label="审核状态" prop="approveStatus" width="160" align="center">
        <template slot-scope="scope">
          <span @click="handleApprove(scope.row)" :style="{'color': colors(scope.row.approveStatus), 'cursor': 'pointer'}">{{ scope.row.approveStatus }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="150">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="启用"
            inactive-value="停用"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" width="180"/>
      <el-table-column label="创建人" prop="createBy" width="160" align="center"/>
      <el-table-column label="更新人" prop="updateBy" width="160" align="center"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="修改时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="120" class-name="small-padding fixed-width" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleDetail(scope.row)"
          >明细</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改食材配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="680px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-form-item label="供应商" prop="remark">
            <el-select v-model="form.vendorId" placeholder="请选择供应商" clearable :style="{width: '100%'}">
              <el-option v-for="(item, index) in vendorOptions" :key="index" :label="item.label"
                        :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="请购名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入请购名称" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
          <el-form-item label="请购日期" prop="planTime">
            <el-date-picker v-model="form.planTime" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                            :style="{width: '100%'}" placeholder="选择请请购日期" clearable></el-date-picker>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="form.remark" placeholder="请输入备注" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { list, listAll, get, add, update, del } from "@/api/store/plan/normal";
import { listAll as listAllVendor } from "@/api/store/vendor";
import { getDicts } from "@/api/system/dict/data";
import moment from "moment/moment";
export default {
  name: "NormalPlan",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 食材表格数据
      rowList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      vendorOptions: [],
      menuOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
    this.getType();
  },
  methods: {
    handleExport() {
      this.download('store/plan/normal/export', {
        ...this.queryParams
      }, `normal_plan_${new Date().getTime()}.xlsx`)
    },
    handleApprove(row) {
      if (row.approveStatus === "未提交审批") {
        this.$modal.msgWarning("未提交审批");
      } else {
        this.$router.push("/approve/detail/" + row.approveMissionId);
      }
    },
    colors(status) {
      if (status === "通过") {
        return '#2a9c4a'
      } else if (status === "拒绝") {
        return '#FF0000'
      } else if (status === "审批中") {
        return '#fe9f29'
      } else {
        return '#fe9f29'
      }
    },
    async getType(){
      const {data} = await getDicts('menu_status');
      this.menuOptions = data.map(item=>({label:item.dictLabel,value:item.dictValue}));
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      listAllVendor().then(res => {
        this.vendorOptions = [];
        for (var i = 0; i < res.rows.length; i++) {
          this.vendorOptions.push({
            label: res.rows[i].name,
            value: res.rows[i].id
          });
        }
      })
      list(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
          this.rowList = response.rows;
          this.total = response.total;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      // this.form = {};
      // this.form.status='停用';
      // this.form.planTime= new Date().toISOString().substr(0, 10); // 当前日期
      // this.form.planId ='QGDC'+Date.now();
      this.form = {
        planId:'QGDC'+Date.now(),
        status:'停用',
        planTime:moment().format('yyy-MM-DD')
      };
      this.open = true;
      this.title = "添加";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      get(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            update(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            add(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除编号为"' + row.id + '"的数据项？').then(function() {
        return del(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    handleDetail(row) {
      const id = row.id;
      this.$router.push("/store/plan/detail/" + id);
    },
    handleStatusChange(row) {
      let text = row.status === "启用" ? "启用" : "停用";
      update({
        id: row.id,
        status: row.status
      }).then(response => {
        this.$modal.msgSuccess(text + "成功");
        this.getList();
      });
    },
  }
};
</script>
